from rest_framework.views import exception_handler
from utils.response import APIResponse
from utils.loggers import logger


def common_exception_handler(exc, context):
    """
    自定义异常处理
    """
    logger.error(f'view is {context["view"]}, error message is {str(exc)}')  # 记录日志

    ret = exception_handler(exc, context)  # 返回Response对象

    if not ret:
        # rest framework处理不了的异常
        return APIResponse(code=101, msg='error', result={'detail': str(exc)})

    return APIResponse(code=101, msg='error', result=ret.data)